/**
 * 
 */
package com.shy.base.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

import com.shy.base.vo.AppConstants;

import cn.hutool.core.img.ImgUtil;

/**
 * <p>Title:ImageUtil
 * <p>Description:
 * @author H2013788
 * @date 2020年8月27日
 */
public class ImageUtil {
	
	/**
	 * 给图片添加文字水印，默认文字最大20，默认在右下方
	 * @param inputFile
	 * @param outFile
	 * @param watermarkerText
	 * @author H2013788
	 * @date 2020年8月27日
	 */
	public static void watermarker(File inputFile, File outFile, String watermarkerText) {
		try {
			BufferedImage image = ImageIO.read(inputFile);  
			int srcWidth = image.getWidth();      // 源图宽度
			int srcHeight = image.getHeight();    // 源图高度
			int fontSize = srcWidth/watermarkerText.length() >= 20 ? 20 : srcWidth/watermarkerText.length();
			
            //ClassPathResource classPathResource = new ClassPathResource("MSYH.TTC");
            //InputStream in = classPathResource.getInputStream();
            //Font fontLoad = FontUtil.createFont(in);
			
            // 复制一个新的对象，此处必须如此
            Font font = AppConstants.WATER_MARKER_FONT.deriveFont(Font.BOLD, fontSize);
			int xPosition = 0;
			if((srcWidth - fontSize * watermarkerText.length()) / 2 - 10  > 0) {
				xPosition = (srcWidth - fontSize * watermarkerText.length()) / 2 - 10;
			}
			//图片添加水印
			ImgUtil.pressText(inputFile, 
					outFile, 
					watermarkerText, 
					Color.WHITE, 
					font,  //文字大小为图片宽度/字数
					xPosition, 
					srcHeight / 2 - 10,  //文字距离底部20像素
					1.0f);
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	

	public static void main(String[] args) {
		File inputFile = new File("E:\\1.jpeg");
		File outFile = new File("E:\\2.jpg");
		String watermarkerText = "测试水印测试水印";
		watermarker(inputFile, outFile, watermarkerText);
	}
	
}
